package org.jmsmith.utilities.io;

import java.io .*;
import java.util.Objects;
import java.util.zip .*;

public class Compressor {

    public static void main(String[] args) {
        try {
            var dirToCompress = new File(args[1]);
            var fos = new FileOutputStream(args[2]);
            var zipOut = new ZipOutputStream(fos);

            if (dirToCompress.exists() && dirToCompress.isDirectory()) {
                // Compress each file in the directory and its subdirectories
                compressDirectory(dirToCompress, dirToCompress.getName(), zipOut);

                // Close the ZipOutputStream
                zipOut.close();
                fos.close();
            } else {
                throw new IOException("Requested compression file is not directory <" + dirToCompress + ">");
            }
            System.out.println("Directory compressed successfully!");
        } catch (IOException e) {
            System.err.println("Failed to compress directory: " + e.getMessage());
        }
    }

    static void compressDirectory(File fileToCompress, String fileName, ZipOutputStream zipOut) throws IOException {
        if (fileToCompress.isDirectory()) {
            // Compress each file in the directory and its subdirectories
            for (File file : Objects.requireNonNull(fileToCompress.listFiles())) {
                compressDirectory(file, fileName + "/" + file.getName(), zipOut);
            }
        } else {
            var fis = new FileInputStream(fileToCompress);
            var zipEntry = new ZipEntry(fileName);
            zipOut.putNextEntry(zipEntry);

            var bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zipOut.write(bytes, 0, length);
            }

            fis.close();
        }
    }
}

